package com.xsm.ppsecret.presenter;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.gson.Gson;
import com.xsm.ppsecret.App;
import com.xsm.ppsecret.config.Authority;
import com.xsm.ppsecret.model.PwdEntry;
import com.xsm.ppsecret.sql.DBHelper;
import com.xsm.ppsecret.sql.DataContracts;
import com.xsm.ppsecret.ui.implview.IPwdActivity;
import com.xsm.ppsecret.util.JsonUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: Xiasem
 * Email: xiasem@163.com
 * Date: 17-4-13.
 */

public class PwdPresenter extends BasePresenter {
    private static final String TAG = "PwdPresenter";
    private IPwdActivity mPwdActivity;
    public PwdPresenter(IPwdActivity pwdActivity) {
        mPwdActivity = pwdActivity;
    }

    public void delete(final Context context, final PwdEntry pwdEntry) {
        Single.create(new SingleOnSubscribe<Integer>() {
            @Override
            public void subscribe(SingleEmitter<Integer> e) throws Exception {
                DBHelper dbHelper = new DBHelper(context);
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                int delete = database.delete(DataContracts.PWDS.TABLE_NAME, "_id=?", new String[]{String.valueOf(pwdEntry.getId())});
                Integer integer = delete;
                e.onSuccess(integer);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onSuccess(Integer value) {
                        mPwdActivity.deleteSuccess(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError: " + e.getMessage());
                        mPwdActivity.deleteError();
                    }
                });
    }

    public void loadData(final Context context) {
        Single.create(new SingleOnSubscribe<ArrayList<PwdEntry>>() {
            @Override
            public void subscribe(SingleEmitter<ArrayList<PwdEntry>> e) throws Exception {
                ArrayList<PwdEntry> list = loadDataFromSqlite(context);
                if (list != null && list.size() > 0) {
                    e.onSuccess(list);
                } else {
                    e.onError(new Throwable("list is null or list.size() = 0"));
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<ArrayList<PwdEntry>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onSuccess(ArrayList<PwdEntry> value) {
                        mPwdActivity.loadSuccessed(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mPwdActivity.loadError("没有任何数据");
                    }
                });
    }

    private ArrayList<PwdEntry> loadDataFromSqlite(Context context) {
        ArrayList<PwdEntry> list = null;
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        Cursor cursor = database.query(DataContracts.PWDS.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                "_id desc",
                null
        );
        if (cursor != null) {
            list = new ArrayList<>();
            while (cursor.moveToNext()) {
                int json = cursor.getColumnIndex(DataContracts.PWDS.JSON);
                String str = cursor.getString(json);

                if (str != null && !str.isEmpty()) {
                    PwdEntry pwdEntry = JsonUtils.getInstance().deserialize(str, PwdEntry.class);
                    int index = cursor.getColumnIndex(DataContracts.PWDS._ID);
                    int id = cursor.getInt(index);
                    pwdEntry.setId(id);
                    if (App.getInstance().authority == Authority.ROOT) {
                        list.add(pwdEntry);
                    } else if (App.getInstance().authority == Authority.FIRST_GRADE) {
                        int authorityInt = cursor.getColumnIndex(DataContracts.PWDS.AUTHORITY);
                        int authority = cursor.getInt(authorityInt);
                        if (authority == Authority.FIRST_GRADE || authority == Authority.SECOND_GRADE) {
                            list.add(pwdEntry);
                        }
                    } else if (App.getInstance().authority == Authority.SECOND_GRADE) {
                        int authorityInt = cursor.getColumnIndex(DataContracts.PWDS.AUTHORITY);
                        int authority = cursor.getInt(authorityInt);
                        if (authority == Authority.SECOND_GRADE) {
                            list.add(pwdEntry);
                        }
                    }
                }
            }
            cursor.close();
        }
        return list;
    }
}
